package com.mxx.common.utils;


import com.mxx.common.exception.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author itzgyw
 * @Date 2020-01-30
 * @Time 23:40
 * @Description:
 */
@Slf4j
public class InputStreamUtil {

    public static byte[] readBytes(InputStream inputStream) throws IOException {
        byte[] b = new byte[1024];
        int len;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            while ((len = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, len);
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            String error = String.format(" read inputStream exception :{exName:%s,msg:%s}", ClassUtils.getQualifiedName(e.getClass()), e.getMessage());
            log.error(error);
            throw new IOException(error);
        } finally {


        }

    }

    public static StringBuffer read(InputStream inputStream, Charset charset) throws IOException {
        byte[] b = new byte[1024];
        int len = 0;
        StringBuffer sb = new StringBuffer();
        try {
            while ((len = inputStream.read(b)) != -1) {
                sb.append(new String(b, 0, len, charset));
            }
        } catch (Exception e) {
            String error = String.format(" read inputStream exception :{exName:%s,msg:%s}", ClassUtils.getQualifiedName(e.getClass()), e.getMessage());
            log.error(error);
            throw new IOException(error);
        }
        return sb;
    }

    public static StringBuffer read(InputStream inputStream) throws IOException {
        return read(inputStream, StandardCharsets.UTF_8);
    }

}
